import { DemoBlock } from '@/components/demos-util';
import { type DetailResult } from '@/pages/types/type';
import { checkAuthorize } from '@/utils/authorize';
import { Content, Page } from '@alita/flow';
import {
  setPageNavBar,
  useLocation,
  useNavigate,
  useSearchParams,
} from 'alita';
import {
  Button,
  Card,
  Cascader,
  Divider,
  DotLoading,
  Form,
  Input,
  NavBar,
  Radio,
  Result,
  Space,
  Toast,
} from 'antd-mobile';
import type { CascaderRef } from 'antd-mobile/es/components/cascader';
import { RefObject, useEffect, useState } from 'react';

import { type DeviceNeedRegister } from '@/pages/types/type';
import { getRequestInit, postRequestInit, urlPrefix } from '@/utils/http';
import { useModel } from 'alita';
import { AntOutline, RightOutline } from 'antd-mobile-icons';
import styles from './index.less';
const numberFormator = new Intl.NumberFormat();

export default () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [searchParams, setSearchParams] = useSearchParams();
  const [tokening, setTokening] = useState<boolean>(true);
  const [tokenFail, setTokenFail] = useState<string | undefined>(undefined);
  const [authOK, setAuthOK] = useState<boolean>(false);
  const [loadFails, setLoadFails] = useState<string[]>([]);
  const [loadOK, setLoadOK] = useState<string | undefined>(undefined);
  const [loadingTimes, setLoadingTimes] = useState<number>(0);

  // 提交时状态控制
  const [ing, setIng] = useState<boolean>();
  const [fail, setFail] = useState<string>();
  const [success, setSuccess] = useState<string>();
  //type  yll ={value:string,lable:string }

  const [need, setNeed] = useState<DeviceNeedRegister>();
  const [deviceId, setDeviceId] = useState<number>();

  const [clinicalDepartments, setClinicalDepartments] = useState<
    {
      value: string;
      label: string;
      children?: { value: string; label: string }[];
    }[]
  >([]);

  type FieldModal = {
    deviceSerialNumber: string;
    updatedAt: string;
    meta: string;
    ecgRemote: string;
  };
  const [form] = Form.useForm<FieldModal>();

  const model = useModel('useAuthModel');
  useEffect(() => {
    setPageNavBar({
      pagePath: location.pathname,
      navBar: {
        hideNavBar: true,
        pageTitle: `设备注册`,
        pageBackground: '#eee',
      },
    });
    checkAuthorize(
      (x) => setTokening(x),
      (y) => {
        console.log(`token检查完成，是否通过授权：${y}`);
        setAuthOK(y);
      },
      (z) => setTokenFail(z),
      model,
    );
  }, []);

  function load() {
    if (authOK) {
      let times = 2;
      // 加载医院及部门
      fetch(
        `${urlPrefix}/api/clinical-department-handle/get-clinical-departments`,
        getRequestInit(),
      )
        .then(async (rsp: Response) => {
          if (rsp.ok) {
            await rsp
              .json()
              .then(
                ({
                  data,
                  code,
                  msg,
                }: DetailResult<{ value: string; label: string }[]>) => {
                  if (code === 0) {
                    if (data) {
                      setClinicalDepartments(data!);
                    }
                    setLoadOK(msg);
                  } else {
                    setLoadFails([...loadFails, msg]);
                  }
                },
              )
              .catch((reason) => {
                setLoadFails([...loadFails, reason]);
              });
          }
        })
        .catch((reason: any) => {
          console.error(reason);
          setLoadFails([...loadFails, `加载部门：${reason}`]);
        })
        .finally(() => {
          setLoadingTimes(--times);
        });
      // 加载待注册设备信息
      fetch(
        `${urlPrefix}/api/rayplatform/device-need-register/detail/${searchParams.get(
          'id',
        )}`,
        getRequestInit(),
      )
        .then(async (rsp: Response) => {
          if (rsp.ok) {
            await rsp
              .json()
              .then(({ data, code, msg }: DetailResult<DeviceNeedRegister>) => {
                if (code === 0) {
                  if (data) {
                    setNeed(data!);
                    form.setFieldsValue({
                      deviceSerialNumber: data!.deviceSerialNumber,
                      meta: data!.meta,
                      ecgRemote: data!.ecgRemote,
                      updatedAt: data!.updatedAt,
                    });
                    if (data!.registrantName) {
                      Toast.show({
                        icon: 'fail',
                        content: `设备已由${
                          data!.registrantName
                        }注册，请不要重复操作`,
                      });
                    }
                  }
                  setLoadOK(msg);
                } else {
                  setLoadFails([...loadFails, msg]);
                }
              })
              .catch((reason) => {
                setLoadFails([...loadFails, reason]);
              });
          }
        })
        .catch((reason: any) => {
          console.error(reason);
          setLoadFails([...loadFails, `加载部门：${reason}`]);
        })
        .finally(() => {
          setLoadingTimes(--times);
        });
    } // end if authOK
  }
  useEffect(load, [authOK]);

  const onFinish = (values: FieldModal) => {
    // Dialog.alert({
    //   content: <pre>{JSON.stringify(values, null, 2)}</pre>,
    // });
    // return;
    const url = '/api/device-handle/register';
    const requestInit: RequestInit = postRequestInit({
      ...values,
      version: 'OK',
    });
    let response: Promise<Response> = fetch(`${urlPrefix}${url}`, requestInit);
    response
      .then(async (rsp: Response) => {
        if (rsp.ok) {
          rsp
            .json()
            .then(async (x: DetailResult<number>) => {
              const { data, code, msg } = x;
              if (code === 0) {
                setSuccess(msg);
                setDeviceId(data!);
              } else {
                setFail(msg);
              }
            })
            .catch((reason) => {
              setFail(reason);
              console.error(`${url} catch in 最内层!`);
            })
            .finally(() => {
              console.log(`finally in 最内层:${url}`);
            });
        } else {
          setFail(`rsp not OK![${url}]`);
          console.log(`!!! rsp not ok! [${url}]`);
        }
      })
      .catch((reason: any) => {
        console.error(reason);
        setFail(`发生错误：${reason}[${url}]`);
        console.error(`${url} catch in 最外层`);
      })
      .finally(() => {
        setIng(false);
        console.log(`finally in 最外层:${url}`);
      });
  };

  if (tokening) {
    return (
      <div style={{ color: '#00b578' }}>
        <DotLoading color="currentColor" />
        <span>正在授权...</span>
      </div>
    );
  }

  if (loadingTimes > 0) {
    return (
      <div style={{ color: '#00b578' }}>
        <DotLoading color="currentColor" />
        <span>正在载入,剩余{loadingTimes}个请求...</span>
      </div>
    );
  }

  return (
    <Page>
      <Content>
        <DemoBlock padding={8}>
          <NavBar
            left={
              <Button
                color="primary"
                size="mini"
                shape="rounded"
                onClick={() => navigate('/')}
              >
                首
              </Button>
            }
            // 未定义导航栏右侧内容！
            onBack={() => navigate(-1)}
          >
            设备注册
          </NavBar>
        </DemoBlock>

        <Card
          title={
            <div style={{ fontWeight: 'normal' }}>
              {/* <AntOutline style={{ marginRight: '4px', color: '#1677ff' }} /> */}
              设备注册
            </div>
          }
          extra={<RightOutline />}
          // onBodyClick={onBodyClick}
          // onHeaderClick={onHeaderClick}
          style={{ borderRadius: '16px', margin: '10px' }}
        >
          <div className={styles.content}>
            <Form
              form={form}
              layout={'vertical'}
              onFinish={onFinish}
              footer={
                <>
                  {success !== undefined && (
                    <Result
                      status="success"
                      title="成功初始化"
                      description={
                        <Space>
                          <Button
                            size={'small'}
                            type={'button'}
                            color="primary"
                            onClick={() => navigate(-1)}
                          >
                            返回
                          </Button>
                          <Button
                            size={'small'}
                            type={'button'}
                            color="primary"
                            onClick={() =>
                              navigate(`/device/detail?id=${deviceId}`)
                            }
                          >
                            打开
                          </Button>
                        </Space>
                      }
                    />
                  )}
                  {fail !== undefined && (
                    <Result
                      status="error"
                      title="执行失败"
                      description={
                        <Space direction="vertical">
                          {fail}
                          <Divider aria-orientation={'vertical'} />
                          <Button
                            color="default"
                            size="small"
                            onClick={() => setFail(undefined)}
                          >
                            再试一次
                          </Button>
                        </Space>
                      }
                    />
                  )}
                  <Button
                    block
                    type="submit"
                    disabled={
                      !authOK ||
                      ing ||
                      fail !== undefined ||
                      success !== undefined
                    }
                    loading={ing}
                    color="primary"
                    size="large"
                  >
                    {success !== undefined ? '已申请' : '提交'}
                  </Button>
                </>
              }
            >
              <Form.Item
                name="deviceSerialNumber"
                label={'序列号'}
                rules={[{ required: true, message: '序列号' }]}
              >
                <Input disabled maxLength={200} />
              </Form.Item>

              <Form.Item
                name="meta"
                label={'元数据'}
                rules={[{ required: true, message: '元数据' }]}
              >
                <Input disabled maxLength={200} />
              </Form.Item>

              <Form.Item
                name="ecgRemote"
                label={'请求注册平台'}
                rules={[{ required: true, message: '请求注册平台' }]}
              >
                <Input disabled maxLength={200} />
              </Form.Item>

              <Form.Item
                name="updatedAt"
                label={'请求时间'}
                rules={[{ required: true, message: '请求时间' }]}
              >
                <Input disabled maxLength={200} />
              </Form.Item>

              <Form.Item
                name="IP"
                disabled
                label={'IP来源地'}
                rules={[{ required: true, message: 'IP来源地' }]}
                initialValue={'广东（开发中）'}
              >
                <Input disabled maxLength={200} />
              </Form.Item>

              <Form.Item
                name="clinicalDepartment"
                label="医院科室"
                onClick={(e: any, ref: RefObject<CascaderRef>) => {
                  console.log(e);
                  console.log(ref);
                  ref.current?.open();
                }}
                rules={[{ required: true, message: '部门科室' }]}
                trigger="onConfirm"
                validateTrigger="onConfirm"
              >
                <Cascader options={clinicalDepartments}>
                  {(items) => {
                    return items.every((item) => item === null)
                      ? '未选择'
                      : items.map((item) => item?.label ?? '未选择').join('-');
                  }}
                </Cascader>
              </Form.Item>

              <Form.Item
                name="name"
                label={'名称'}
                rules={[{ required: true, message: '名称' }]}
              >
                <Input maxLength={200} />
              </Form.Item>

              <Form.Item
                name="code"
                label={'编码'}
                rules={[{ required: true, message: '编码' }]}
              >
                <Input maxLength={200} />
              </Form.Item>

              <Form.Item
                name="type"
                label={'类型'}
                rules={[{ required: true, message: '类型' }]}
              >
                <Radio.Group>
                  <Space direction={'vertical'}>
                    <Radio value="PC">PC客户端</Radio>
                    <Radio value="ECG">心电图机</Radio>
                    {/* <Radio value="Blue">采集器</Radio> */}
                  </Space>
                </Radio.Group>
              </Form.Item>

              <Form.Item
                name="dataFileType"
                label={'数据文件类型'}
                rules={[{ required: true, message: '类型' }]}
              >
                <Radio.Group>
                  <Space direction={'vertical'}>
                    {[
                      { label: '三锐专用数据文件格式', value: 'RAY' },
                      { label: 'HL7XML', value: 'HL7XML' },
                    ].map((x) => (
                      <Radio key={x.value} value={x.value}>
                        {x.label}
                      </Radio>
                    ))}
                  </Space>
                </Radio.Group>
              </Form.Item>

              <Form.Item
                name="reportFileType"
                label={'报告文件类型'}
                rules={[{ required: true, message: '类型' }]}
              >
                <Radio.Group>
                  <Space direction={'vertical'}>
                    {[
                      { label: '不上传', value: 'DontUpload' },
                      { label: 'PDF', value: 'PDF' },
                    ].map((x) => (
                      <Radio key={x.value} value={x.value}>
                        {x.label}
                      </Radio>
                    ))}
                  </Space>
                </Radio.Group>
              </Form.Item>
            </Form>
          </div>
        </Card>
      </Content>
    </Page>
  );
};
